<template>
  <view class="preview" :style="{ backgroundImage: `url(${url})` }">
    <!-- #ifndef H5 -->
    <view style="height: 44px"></view>
    <!-- #endif -->
    <view class="global-m flex-1">
      <view v-if="!show" class="d-flex preview-check">
        <view>
          <wd-icon
            @click="toBack"
            color="#fff"
            size="26"
            name="arrow-left"
          ></wd-icon>
        </view>
        <view class="flex-1 d-flex-center">
          <wd-checkbox
            v-if="!show"
            checked-color="rgb(158,212,129)"
            v-model="show"
            shape="square"
            @change="showChange"
            >预览</wd-checkbox
          >
        </view>
      </view>
    </view>
    <view class="preview-action" v-if="!show">
      <view>{{ target.name }}</view>
      <view style="margin-top: 1rem">
        <!-- #ifdef MP-WEIXIN -->
        <wd-button @click="download('download')" size="large">下载</wd-button>
        <!-- #endif -->
        <!-- #ifndef MP-WEIXIN -->
        <wd-button @click="download('set')" size="large">设为壁纸</wd-button>
        <!-- #endif -->
      </view>
      <view class="preview-action_love">
        <view>
          <image
            v-if="likeState"
            @click="setUnLike"
            style="width: 30px"
            mode="widthFix"
            src="/static/assets/images/aixin-like.png"
          />
          <image
            v-else
            @click="setLike"
            style="width: 30px"
            mode="widthFix"
            src="/static/assets/images/aixin.png"
          />
          <view>{{ likes }}</view>
        </view>
      </view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <video
      class="background-video"
      :src="url"
      autoplay
      loop
      muted
      playsinline
    ></video>
    <!-- #endif -->
    <!-- #ifdef APP -->
    <DomVideoPlayer
      class="background-video"
      :src="url"
      autoplay
      objectFit="cover"
      :poster="target.url"
      loop
      :controls="false"
      muted
    />
    <!-- #endif -->
  </view>
  <vip ref="visibleRef"></vip>
  <view @click="show = false" class="preview-fixed" v-if="show">
    <view style="height: 124px"></view>
    <view class="d-flex-center" style="font-size: 60px; color: #fff;">
      {{ dayjs().format("HH:mm") }}
    </view>
    <view class="d-flex-center" style="font-size: 22px; color: #fff;">
      {{ dayjs().format("YYYY-MM-DD") }}
      <view style="margin-left: 20px">星期{{dayjs().locale('zh-cn').format("dd")}}</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad, onUnload, onHide } from "@dcloudio/uni-app";
import { innerAudioContext } from "@/hooks/utils";
import dayjs from "dayjs";
import 'dayjs/locale/zh-cn'; // 需要引入中文语言包
 
dayjs.locale('zh-cn'); // 设置为中文

// #ifdef APP
const jnWallpaper = uni.requireNativePlugin('jc-Wallpaper')
// #endif
const channelId = ref('Ba-KeepAlive'), channelName = ref('Ba-KeepAlive'), title = ref('Ba-KeepAlive'), content = ref('Ba-KeepAlive is running'), dataResult = ref(''), type = ref(undefined)
import store from "../../store";
import Vip from '@/section/vip.vue'
const likeState = ref(false);
const previewState = ref(false);
const show = ref(false),
  url = ref(""),
  name = ref("");
const visibleRef = ref(null)
const category = ref("");
const target = ref({});
const likes = ref(0),
  assUrl = ref(""),
  association = ref("");
const toBack = () => {
  uni.navigateBack();
};
const userInfo = computed(() => {
  return store.state.value.userInfo;
});

onUnload(() => {
  innerAudioContext && innerAudioContext.pause();
});
onHide(() => {
  console.log("页面已经隐藏");
});
onLoad((params) => {
  // console.log(params);
  assUrl.value = params.url;
  association.value = params.association;
  getLikes(params.url);
  getLikeState()
  target.value = {
    ...params,
    association: params.association,
    name: params.name,
  };
  getUrlOss();
  if (params.category == "dynamic-wallpaper") {
    url.value = params.association;
    name.value = params.name;
    category.value = params.category;
    // #ifdef MP-WEIXIN
    innerAudioContext.src = url.value;
    innerAudioContext.autoplay = true;
    innerAudioContext.play();
    // #endif
    return;
  }
  name.value = decodeURIComponent(params.name);
  url.value = params.url;
});
const getUrlOss = (url) => {
  uni.request({
    url: '/api/wallpaper/oss/url?url=' + assUrl.value,
    method: 'GET',
    success: (res) => {
      target.value = {...target.value, ...res.data };
      console.log(target.value)
    }
  })
}
const getLikes = (url) => {
  uni.request({
    url: "/api/wallpaper/like/count?url=" + url,
    method: "GET",
    success: (res) => {
      likes.value = res.data;
    },
  });
};
const getLikeState = () => {
  uni.request({
    url: '/api/wallpaper/like/ready',
    method: 'POST',
    data: {
      username: uni.getStorageSync("wpa_username"),
      url: assUrl.value,
    },
    success: (res) => {
      likeState.value = res.data.like;
    }
  });
}
const setUnLike = () => {
  if (!uni.getStorageSync("wpa_username")) {
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    return;
  }
  uni.request({
    url: "/api/wallpaper/like/cancel",
    method: "POST",
    data: {
      username: uni.getStorageSync("wpa_username"),
      url: assUrl.value,
    },
    success: (res) => {
      if (!res.data.like) {
        uni.showToast({
          title: "取消点赞成功",
          icon: "none",
        });
        likes.value -= 1;
        getLikeState()
      }
    },
  })
}
const setLike = () => {
  if (!uni.getStorageSync("wpa_username")) {
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    return;
  }
  uni.request({
    url: "/api/wallpaper/like/add",
    method: "POST",
    data: {
      username: uni.getStorageSync("wpa_username"),
      url: assUrl.value,
      association: decodeURIComponent(association.value),
      category: target.value.category,
    },
    success: (res) => {
      if (res.data.like) {
        uni.showToast({
          title: "已经点赞了",
          icon: "none",
        });
      } else {
        uni.showToast({
          title: "点赞成功",
          icon: "none",
        });
        likes.value += 1;
        getLikeState()
      }
    },
  });
};
const addToDownloadList = () => {
  uni.request({
    url: "/api/wallpaper/download/add",
    method: "POST",
    data: {
      url: target.value.url,
      association: target.value.association,
      username: uni.getStorageSync("wpa_username"),
      category: target.value.category,
    },
  });
};
const addToSetList = () => {
  uni.request({
    url: "/api/wallpaper/set/add",
    method: "POST",
    data: {
      url: target.value.url,
      association: target.value.association,
      username: uni.getStorageSync("wpa_username"),
      category: target.value.category,
    },
  });
};
const download = (wallpaperType) => {
  const username = uni.getStorageSync("wpa_username");
  if (!username) {
    uni.showModal({
      title: "提示",
      content: "请先登录,才能下载壁纸",
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: "/pages/login/index",
          });
        }
      },
    });
    return;
  }
  if (!userInfo.value.vip) {
    visibleRef.value.openVisible();
    return;
  }
  uni.showToast({
    title: "正在保存",
    icon: "loading",
  });
  if( wallpaperType == 'download' ){
    addToDownloadList();
  }
  if( wallpaperType =='set' ){
    addToSetList();
  }
  if (category.value == "dynamic-wallpaper") {
    uni.downloadFile({ 
			url: url.value,
			success: (res) => {
				// #ifdef APP-PLUS
				if (plus.os.name.toLowerCase() === "android") {
				  // 设置壁纸
				  var WallpaperManager = plus.android.importClass(
				    "android.app.WallpaperManager"
				  );
				  //console.log(WallpaperManager);
				  var Main = plus.android.runtimeMainActivity();
				  var wallpaperManager = WallpaperManager.getInstance(Main);
				  var filePath = res.tempFilePath.replace("file://", "");
				  filePath = plus.io.convertLocalFileSystemURL(filePath);
					jnWallpaper.setDynamicWallpaper({
					    url: filePath
					})
				  uni.setStorageSync('wallpaperState', 'OPEN')
					uni.setStorageSync('wallpaperVoice', 'OPEN')
				}
				// #endif
        // #ifndef APP-PLUS
        uni.saveVideoToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (res) => {
            uni.showToast({
              title: "保存成功",
              icon: "none",
            });
          },
        });
        // #endif
			},
			fail: (error) => {
				console.log(error)
			}
		})
    
  } else {
    // #ifdef APP-PLUS
    if (plus.os.name.toLowerCase() === "android") {
      // 设置壁纸
      var WallpaperManager = plus.android.importClass(
        "android.app.WallpaperManager"
      );
      //console.log(WallpaperManager);
      var Main = plus.android.runtimeMainActivity();
      var wallpaperManager = WallpaperManager.getInstance(Main);
      //console.log(wallpaperManager);
      //var wpm = plus.android.importClass(wallpaperManager);
      var BitmapFactory = plus.android.importClass(
        "android.graphics.BitmapFactory"
      );
      uni.downloadFile({
        url: url.value,
        complete: (e) => {
          uni.hideLoading();
        },
        success: (e) => {
          var filePath = e.tempFilePath.replace("file://", "");
          console.log(e.tempFilePath);
          //console.log(filePath);
          filePath = plus.io.convertLocalFileSystemURL(filePath);
          //console.log(filePath);
          var bitmap = BitmapFactory.decodeFile(filePath);
          jnWallpaper.setStaticWallpaper({
						url:plus.io.convertLocalFileSystemURL(e.tempFilePath)
					})
          //console.log(bitmap);
          try {
            //wallpaperManager.suggestDesiredDimensions(, );
            // wallpaperManager.setBitmap(bitmap);
            // bitmap.recycle();
            // wallpaperManager.setBitmap(
            //   bitmap,
            //   null,
            //   true,
            //   WallpaperManager.FLAG_LOCK
            // ); //设置锁屏
            uni.showToast({
              icon: "none",
              title: "壁纸设置成功",
            });
          } catch (e) {
            console.log(e);
            uni.showToast({
              icon: "none",
              title: "壁纸设置失败" + e,
            });
          }
        },
        fail: () => {
          uni.showToast({
            icon: "none",
            title: "壁纸设置失败",
          });
        },
      });
    } else {
      uni.showToast({
        title: "此功能仅限安卓设备使用",
        icon: "none",
        duration: 2000,
      });
    }
    // #endif
    // #ifndef APP-PLUS
    uni.getImageInfo({ src: url.value }).then((res) => {
      uni.saveImageToPhotosAlbum({
        filePath: res.path,
        success: () => {
          console.log("suc");
          uni.showToast({
            title: "保存成功",
            icon: "none",
          });
        },
        fail: (err) => {
          console.log("err", err);
        },
      });
    });
    // #endif
  }
};
const showChange = (e) => {
}
</script>

<style lang="scss" scoped>
.preview {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: url("http://124.223.41.167:8080/mobile/static/images/c1.png")
    center center no-repeat;
  background-size: cover;
}
.preview-check {
  --wot-checkbox-label-color: #fff;
}
.preview-action {
  position: relative;
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  background: rgba(0, 0, 0, 0.3);
  --wot-button-primary-bg-color: rgb(220, 63, 100);
}
.preview-action_love {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 0.85rem;
}
.background-video {
  position: absolute;
  width: 100vw;
  height: 100vh;
  object-fit: cover; /* 确保视频覆盖整个容器 */
  top: 0;
  left: 0;
  z-index: -1; /* 确保视频在其他内容下方 */
}
.preview-fixed{
  position: fixed;
  width: 100vw;
  height: 100vh;
  left: 0;
  top: 0;
  z-index: 9999;
}
</style>